const {
    onceOfSameParam,
    stringValidator: {
        isInteger,
    },
    CombinedPredicate: {
        not,
    },
    listToTree,
    treeToList,
    nodeBridgeUtil,
    isNullOrUndefined,
    arrayToMap,
} = rx

const validate = RxFormValidator.generate([
    RxElemValidator.notBlank('name', '[名称] 不能为空'),
    RxElemValidator.notBlank('code', '[键值] 不能为空'),
    RxElemValidator.notBlank('status', '[状态] 不能为空'),
    RxElemValidator.notBlank('order', '[排序] 不能为空'),
    RxElemValidator.notBlank('type', '[类型] 不能为空'),

    RxElemValidator.limitLen('code', '[键值] 长度最大为 10 位', 10),
    RxElemValidator.limitLen('type', '[类型] 长度最大为 3 位', 3),
    RxElemValidator.limitLen('name', '[名称] 长度最大为 50 位', 50),
    RxElemValidator.limitLen('order', '[排序] 长度最大为 5 位', 5),

    RxElemValidator.create('code', '[键值] 必须为整数', not(isInteger)),
])


const app = new BasicTableVue({
    data() {
        return {
            api: sysBaseCodeApi,
            sysBaseCode: new SysBaseCode(),
            updateVisible: false,
            dtitle: '',
            formLabelWidth: '50px',
            columns: [
                new TableColumn({prop: 'name', title: '名称'}),
                new TableColumn({prop: 'code', title: '键值'}),
                new TableColumn({prop: 'status', title: '状态', customComponent: true}),
                TableColumn.generate({prop: 'order', title: '排序', sortAs: 's_order'}),
                TableColumn.generate({prop: 'parent', title: '父类'}),
                new TableColumn({prop: 'comments', title: '备注'}),
                new TableColumn({prop: 'operating', title: '操作', customComponent: true}),
            ],
            statusImgList: {'1': 'yes.gif', '2': 'no.gif'},
            isAdd: false,
            // 数据默认字段
            defaultProps: {
                parent: 'parentId',   // 父级唯一标识
                value: 'code',          // 唯一标识
                label: 'name',       // 标签显示
                children: 'child', // 子级
            },
            baseCodeMap: new Map(),
            parentCodeTree: [],
            parentCodeList: [],
            parentCodeMap: new Map(),
        }
    },
    methods: {
        createForm() {
            return new SysBaseCode({
                typeAction: 13,
            })
        },
        async typeActionChange() {
            this.searchPage()
            this.init()
            //this.calcParentCodeTree()
        },
        statusImg(val) {
            return '/static/img/' + this.statusImgList[val]
        },
        addInfo() {
            this.dtitle = "新增"
            this.updateVisible = true
            this.sysBaseCode = {}
            this.isAdd = true
            this.parentCodeMap = arrayToMap(this.parentCodeList, ({code}) => code, ({name}) => name)
        },
        async updateInfo(row) {
            this.dtitle = "修改"
            row.status = parseInt(row.status)
            this.sysBaseCode = _.cloneDeep(row)
            this.updateVisible = true
            this.isAdd = false
            // this.parentCodeTree = listToTree(treeToList(this.parentCodeTree, {
            //     bridge: nodeBridgeUtil.bridge({parentId: 'parent'}),
            // })
            //     .filter(({id}) => row.id !== id), {
            //     bridge: nodeBridgeUtil.bridge({parentId: 'parent'}),
            //     isRoot: ({parent}) => !parent || parent === 0,
            // })
            this.parentCodeMap = arrayToMap(this.parentCodeList.filter(en => en.code !== row.code), ({code}) => code, ({name}) => name)
        },
        async updateOrAddData() {
            this.sysBaseCode.type = this.form.typeAction
            this.sysBaseCode.delFlag = '0'
            if (!(await validate(this.sysBaseCode))) {
                return
            }
            if (this.sysBaseCode.id === undefined && (await sysBaseCodeApi.existsByTypeAndCode(this.sysBaseCode.type, this.sysBaseCode.code))) {
                await rxPrompt.msg("[键值] 已存在");
                return
            }
            let res = await sysBaseCodeApi.updateOrAdd(this.sysBaseCode)
            var successTitle = `${this.dtitle} 成功`;
            var dangerTitle = `${this.dtitle} 失败`;
            if (await ajaxOption({
                res,
                danger: dangerTitle,
                success: successTitle,
            })) {
                this.updateVisible = false
                this.typeActionChange()
            }
        },
        async del({id}) {
            if (isNullOrUndefined(id)) {
                await rxPrompt.msg('删除失败')
                return
            }
            if (await rxPrompt.confirm('你确认要删除该记录吗?？', ['确认', '取消']) && await ajaxOption({
                res: this.api.deleteById(id),
                danger: '删除失败',
                success: '删除成功',
            })) {
                await this.typeActionChange()
            }
        },
        async calcParentCodeTree() {

            const listToTree1 = listToTree(await this.api.selectListByType(this.form.typeAction), {
                bridge: nodeBridgeUtil.bridge({parentId: 'parent'}),
                isRoot: ({parent}) => !parent || parent === '0',
            });
            //修复工具代码不兼容的问题
            var val = [];
            if (Array.isArray(listToTree1)) {
                val = listToTree1;
            } else {
                if (Object.keys(listToTree1).length === 1) {
                    val = Array.of(listToTree1);
                }
            }

            this.parentCodeTree = val;

        },
        async init() {
            //await this.calcParentCodeTree()
            this.parentCodeList = await this.api.selectListByType(this.form.typeAction)
        },
    },
    computed: {
        fieldFormatter() {
            return fieldFormatter
        },
    },

})
